var appPath = getAppPath();

$(function(){
	// 来源
	$("#queryFpFrom").combobox({
		url:appPath+'/itbCom/getFpFrom4Combo.action?blkFlg=1',
		valueField:'from_value',
		textField:'from_text',
		onSelect:function(row){
			// TODO
		}
	});
	
	initJspGrid();
});

// 样版列表初始化
function initJspGrid(){
	
	$('#invoiceGrid').datagrid({
	    url:appPath + "/itbInvoice/getInvoiceInfoPg.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
//	    frozenColumns:[[
//	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
//	    ]],
	    columns:[[
  		    {field:'downInfo',title:'导出',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(!rowData.inv_id) return "N/A";
  	        		var url = appPath+"/itbInvoiceWeb/downInvoiceInfo.action?invId="+rowData.inv_id;
	        		return "<a href='"+url+"' >下载</a>";
	        	}
		    },
  	        {field:'inv_id',title:'发票ID',width:30,align:'center',sortable:false},
  	        {field:'inv_no',title:'发票编号',width:50,align:'center',sortable:false},	        
	        {field:'user_id',title:'用户ID',width:40,align:'center',sortable:false},
  	        {field:'state',title:'状态',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.inv_id) return "N/A";
	        		var show = getState4Show(value);
	        		return "<a href='javascript:void(0)' onClick='editState("+rowData.inv_id+")'>"+show+"</a>";
	        	}
		    }, 
  	        {field:'title',title:'发票抬头',width:50,align:'center',sortable:false},	        
	        {field:'content',title:'发票内容',width:40,align:'center',sortable:false},
	        {field:'total_fee',title:'发票金额',width:50,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.inv_id) return "N/A";
	        		var show = Number(value||'0')/100;
	        		return show+'元';
	        	}
		    },
	        {field:'order_fee',title:'订单金额',width:50,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.inv_id) return "N/A";
	        		var show = Number(value||'0')/100;
	        		return show+'元';
	        	}
		    },
  	        {field:'taxpayer_id',title:'纳税人识别号',width:50,align:'left',sortable:false},
  	        {field:'bank',title:'开户银行',width:50,align:'left',sortable:false},	        
	        {field:'bank_account',title:'银行帐号',width:50,align:'left',sortable:false},
	        {field:'address',title:'公司地址</br>附属信息',width:50,align:'left',sortable:false},
  	        {field:'mobile',title:'手机号',width:50,align:'left',sortable:false},
//	        {field:'mail_fee',title:'发票邮费',width:80,align:'center',sortable:false,
//  	        	formatter:function(value, rowData, rowIndex){
//	        		if(!rowData.inv_id) return "N/A";
//	        		var show = Number(value||'0')/100;
//	        		return show+'元';
//	        	}
//		    },
	        {field:'tracking_no',title:'运单号',width:50,align:'left',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.inv_id) return '<span style="color:red;">N/A</span>';
	        		var show = (rowData.express||'')+'['+(value||'NULL')+']';
	        		return "<a href='javascript:void(0)' onClick='editExpress("+rowData.inv_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'addr',title:'收货地址',width:100,align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if (value){
		    			return '<span title="'+value+'">'+value+'</span>';
		    		}
		    		return '未知';
		    	}
	        },
	        {field:'create_time',title:'创建时间',width:90,align:'center',sortable:false},
	        {field:'update_time',title:'修改时间',width:90,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
			/*{
				text:'删除发票',
				iconCls:'icon-cancel',
				handler:function(){
					delInvoice();
				}
			}*/
		]
	});
}

//从后台获取数据函数
function getState4Show(value){
	var state = '<span style="color:red">未知</span>';
	switch(Number(value||'0')){
		case 10: state='<span style="color:blue">待支付</span>'; break;
		case 11: state='<span style="color:green">已支付</span>'; break;
		case 12: state='<span style="color:red">支付失败</span>'; break;
		case 20: state='<span style="color:brown">开票中</span>'; break;
		case 22: state='<span style="color:red">开票失败</span>'; break;
		case 30: state='<span style="color:brown">配送中</span>'; break;
		case 40: state='<span style="color:green">完成</span>'; break;
		case 50: state='<span style="color:red">取消</span>'; break;
	}
	return state;
}



//发票状态   编辑
function editState(invId){
	$("#stateDlg").show();
	$('#stateForm').form('clear');
	$("#updDesc").val('');
	$("#updInvNo").html('');

	$("#updInvId").val(invId);
	
	var title = '发票状态';
	var url = appPath + "/itbInvoice/getInvoiceInfoLst.action?inv_id="+ invId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#updInvNo").html(info.inv_no||'');
			$("#updInvState").combobox('select',info.state||0);
			$("#updDesc").val(info.desc||'');
			$("#updRecdInfo").val(JSON.stringify(info||{}));
		}
	});
	
	$("#stateBtn").show();
	$('#stateDlg').window({
		title: title,
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#stateDlg').window('move',{top:20,left:20});
	$('#stateDlg').window('open');
}
function cancelUpdState(){
	$('#stateDlg').window('close');
}
function doUpdState(){
	var id = $("#updInvId").val();
	var state = $("#updInvState").combobox('getValue');
	var desc = $("#updDesc").val();
	var recdInfo = JSON.parse($("#updRecdInfo").val()||'{}');
	
	// 默认更新订单
	var url = appPath+"/itbInvoiceWeb/updInvoice.action";
	var sendData = {
		"invoiceInfo.inv_id": Number(id||"0"),
		"invoiceInfo.state": Number(state || "0"),
		"invoiceInfo.desc": desc||''
	};
	
    $.post(url, sendData, function(data){  
		if (data == "ok") {
			// 添加历史纪录
			var url2 = appPath+"/itbOrdersWeb/addStateHis.action";
			var sendData2 = {
				"stateHisInfo.type": 20,
				"stateHisInfo.trade_obj_id": Number(id||"0"),
				"stateHisInfo.total_fee": recdInfo.total_fee||0,
				"stateHisInfo.user_id": recdInfo.user_id||0,
				"stateHisInfo.state": Number(state || "0"),
				"stateHisInfo.desc": desc||''
			};
			$.post(url2, sendData2, function(data2){
				if(data == "ok") {
					$.messager.alert('提示信息','更新成功','info');
					$('#stateDlg').window('close');
					doQuery();	
				} else {
					$.messager.alert('提示信息','[状态历史]添加失败','info');
				}
			});
			
					
        } else {
        	$.messager.alert('提示信息','更新失败','info');
        }
    });
}



//删除商品 编辑
function delInvoice(){
	var selectInvoice=$("#invoiceGrid").datagrid("getChecked");
	if(!selectInvoice || selectInvoice.length == 0){
		$.messager.alert('提示信息','请选择商品！','warning');
		return;
	}
	for(var i=0; i<selectInvoice.length; i++){
		if(Number(selectInvoice[i].state||'0')==20){
			$.messager.alert('提示信息','不能删除[已上架]商品！','warning');
			return;
		}
	}
	
	$.messager.confirm("确认", "是否确认[删除]所选发票信息？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectInvoice, function(index, item){
					ids = ids + item.inv_id + ",";
				});
				var url = appPath+"/itbInvoiceWeb/delInvoice.action?delIds="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}




//编辑物流信息
function editExpress(dId){
	$("#expressDlg").show();
	$('#expressForm').form('clear');

	$("#expInvId").val(dId);
	
	var url = appPath + "/itbInvoice/getInvoiceInfoLst.action?inv_id="+ dId;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#expInvNo").html(info.inv_no||'');
			$("#editExpress").val(info.express||'');
			$("#editTrackNo").val(info.tracking_no||'');
		}
	});
	
	$("#expressBtn").show();
	$('#expressDlg').window({
		title: '发票物流信息',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#expressDlg').window('move',{top:20,left:20});
	$('#expressDlg').window('open');
}
function cancelUpdExp(){
	$('#expressDlg').window('close');
}
function doUpdExp(){
	var did = $("#expInvId").val();
	var express = $("#editExpress").val()||'';
	var trackNo = $("#editTrackNo").val()||'';
	
	if(trackNo.length<=0){
		return $.messager.alert('提示信息','请填写运单号！','warning');
	}
	
	// 默认更新发票物流信息
	var url = appPath+"/itbInvoiceWeb/updInvoice.action";
	var	sendData = {
		"invoiceInfo.inv_id": Number(did||"0"),
		"invoiceInfo.express": express||'',
		"invoiceInfo.tracking_no": trackNo||''
	};
 $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','更新成功','info');
			$('#expressDlg').window('close');
			doQuery();			
     } else {
     	$.messager.alert('提示信息','更新失败','info');
     }
 });
}
/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	
	var findState = $("#queryFpState").combobox('getValue');
	var findNumber = $("#queryFpNumber").val();
	var findTitle = $("#queryFpTitle").val();
	var findMobile = $("#queryFpMobile").val();
	
	if(findState && Number(findState||'0')>0) queryObject.findFpState = findState;// 发票状态
	if(findNumber && findNumber.length>0) queryObject.findFpNumber = findNumber;	//发票编号
	if(findTitle && findTitle.length>0) queryObject.findFpTitle = findTitle;		  //发票抬头
	if(findMobile && Number(findMobile||'0')>0) queryObject.findFpMobile = findMobile;// 手机
	
	return queryObject;
}

/**
 * 刷新查询数据
 */

function doQuery(){
	$("#invoiceGrid").datagrid('unselectAll');
	$("#invoiceGrid").datagrid('load', getQueryParam());
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}
